<?php
use think\Db;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/* 
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}


/*生成支付二维码
 *$param $app  商户号
 * $param $key 商户 密匙
 * $op  商户收银员号
 * $amount 顶大价格
 * $channel 支付方式1支付宝2微信
 * $local_order_no 订单号
 * $notify_url="http://t1.lxtx001.com/api/index"; 回调地址
 * 
 */
function pay_code($app,$key,$op,$amount,$channel,$local_order_no,$notify_url='',$redirect_url=''){
	$url="http://openapi.caibaopay.com/gatewayOpen.htm?";
	$t=time();
//	$app="H48007350000002";
//	$key="ac8f09abd655bdfc0345f61ddf6d658f";
//	$op="2ec6d8240578a85b0b6949b3a335f98a";
//	$local_order_no=123456789;
	$notify_url=$notify_url?$notify_url:config("notify_url");
	$redirect_url=$redirect_url?$redirect_url:config("redirect_url")."?order_sn=$local_order_no";
	$amount=$amount*100;
	$pt  ="amount=$amount&app=$app&channel=$channel&local_order_no=$local_order_no&operator_id=$op&timestamp=$t";
	$data="amount=$amount&app=$app&channel=$channel&command=caibao.pay.h5&local_order_no=$local_order_no&notify_url=$notify_url&operator_id=$op&redirect_url=$redirect_url&timestamp=$t";
	$pt.="&key=$key";
	$str="amount=1&app=H48007350000002&channel=1&local_order_no=$local_order_no";
	$sign=bin2hex(md5($pt,true));//md5($pt);
	$url.=$data."&sign=$sign";
	$res=file_get_contents($url);
	$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
	$array1 = get_object_vars($jsondecode1);//转换成数组
	$result=$array1['data'];
	$result=get_object_vars($result);
	//$qrcode= 'http://www.vshop88.net/code/code.php?url='.urlencode($result['qrCode']).'&margin=1&size=10';
		//$qrcode = $qrPay->create_erweima($response->qr_code);
	//echo "<img src=$qrcode />";
	return $result['url'];
	exit;
}
	
/**
 * 调用成功
 */
function toSuccess($msg='', $data='') {
		return json(['code'=>200,'msg'=>$msg,'data'=>$data]);
	}
/**
 * 调用失败
 */
function toError($code='', $msg='', $data='') {
		return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
}
	

/**
 * 生成订单号
 */
function order_create_no(){
	return date('YmdHis', time()).rand(8, true);
}

	
/**
 * 手机端调用成功
 */
function toSuccessp($msg='', $data='') {
		return jsonp(['code'=>200,'msg'=>$msg,'data'=>$data]);
	}
/**
 * 手机端调用失败
 */
function toErrorp($code='', $msg='', $data='') {
		return jsonp(['code'=>$code,'msg'=>$msg,'data'=>$data]);
	}	
	
/**
 * 返回格式化后的当前时间
 */
function now_time(){
	return date('Y-m-d H:i:s',time());
}


/**
 * 构建层级（树状）数组
 * @param array  $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid = 'pid', $child_key_name = 'children') {
    $counter = array_children_count($array, $pid);
    if ($counter[0] == 0)
        return false;
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid);
    }

    return $tree;
}


/**
 * 子元素计数器
 * @param $array
 * @param $pid
 * @return array
 */
function array_children_count($array, $pid) {
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}


/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}


/**
 * 数组层级缩进转换
 * @param array $array
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }
    return $list;
}


//日志处理


function logc($text="",$status=""){
	$list['admin_name']=session('admin_name');
	$list['u_id']=session('admin_id');
	$list['ip']=session('ip');
	$list['add_time']=now_time();
	$list['text']=$text;
	$list['status']=$status;
	return Db::name('tg_admin_log')->insert($list);
	
}


/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function load_wechat($type = '')
{
    $wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
    	$config = get_config('wechat_config');
    	$config['cachepath'] = CACHE_PATH . 'wechat';
    	$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}
function load_agent_wechat($type = '',$config)
{
    $wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
    	$config = get_config('wechat_config');
    	$config['cachepath'] = CACHE_PATH . 'wechat';
    	$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}
/**
 * 设置全局配置到文件
 *
 * @param $key
 * @param $value
 * @return boolean
 */
function sys_config_setbykey($key, $value)
{
    $file = ROOT_PATH.'application/extra/log.php';
    $cfg = array();
    if (file_exists($file)) {
        $cfg = include $file;
    }
    $item = explode('.', $key);
    switch (count($item)) {
        case 1:
            $cfg[$item[0]] = $value;
            break;
        case 2:
            $cfg[$item[0]][$item[1]] = $value;
            break;
    }
    return file_put_contents($file, "<?php\nreturn " . var_export($cfg, true) . ";");
}
/**
 * 设置全局配置到文件
 *
 * @param array
 * @return boolean
 */
function sys_config_setbyarr($data)
{
    $file = ROOT_PATH.'application/extra/log.php';
    if(file_exists($file)){
        $configs=include $file;
    }else {
        $configs=array();
    }
    $configs=array_merge($configs,$data);
    return file_put_contents($file, "<?php\treturn " . var_export($configs, true) . ";");
}
/**
 * 获取全局配置
 *
 * @param $key
 * @return array|null
 */
function sys_config_get($key)
{
    $file = ROOT_PATH.'application/extra/log.php';
    $cfg = array();
    if (file_exists($file)) {
        $cfg = (include $file);
    }
    return isset($cfg[$key]) ? $cfg[$key] : null;
}

/**
 * 获取当前request参数数组,去除值为空
 * @return array
 */
function get_query(){
	$param = request()->except(['s']);
	$rst = array();
	foreach($param as $k=>$v){
		if(!empty($v)){
			$rst[$k] = $v;
		}
	}
	return $rst;
}


/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author rainfer <81818832@qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}



/**
 * 获得配置,已oem_id 区分
 */
function get_config($name,$oem_id=1){
	$where['name'] = $name;
	$where['oem_id'] = $oem_id;
	$site_config = db('tg_admin_system')->field('value')->where($where)->find();
    $site_config = unserialize($site_config['value']);
	return $site_config;
}

function sendsms($sign,$mobile,$tempid,$name,$value,$oem_id){
	$cut_time = now_time();
	include_once ('./extend/smsapi/smsDemo.php');
	$msg=sendMess($sign,$mobile,$tempid,$name,$value,$oem_id);
	if($msg->Message=="OK") {
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['message'] 	= '发送成功';
		db('sms_code')->insert($data);
		return true;
	}else{
		$data['mobile'] 	= $mobile;
		$data[$name] 		= $value;
		$data['add_time'] 	= $cut_time;
		$data['result'] 	= 0;
		$data['message'] 	= '发送失败:'.$msg->Message;
		db('sms_code')->insert($data);
		$err=$msg->Message;
		return false;
	}
}
/**
 * 短信发送
 * $mobile 手机号
 * $tempalte 短信模板ID
 * $params 参数
 */
function send_sms($mobile, $template_id, $params, $sign_name,$content=null){
	// 获取短信配置
	$sms_config = get_config('sms_config');
	include_once ('./vendor/alidayu/TopSdk.php');
    date_default_timezone_set('Asia/Shanghai');
	$c = new TopClient;
//	$c -> format = 'json';
//	$c -> simplify = true;
	$c -> appkey = $sms_config['app_key'];
	$c -> secretKey = $sms_config['app_secret'];
	$req = new AlibabaAliqinFcSmsNumSendRequest;
	$req -> setSmsType("normal");
	if($sign_name){
		$req -> setSmsFreeSignName($sign_name);
	}else{
		$req->setSmsFreeSignName("龙信天下");
	}
	if($params){
		$req -> setSmsParam($params);
	}
	$req -> setRecNum($mobile);
	if($content){
		$req->setSmsParam('{"customer":"'.$content.'"}');
	}
	$req -> setSmsTemplateCode($template_id);
	$resp = $c -> execute($req);
	return $resp;
}

//根据设置名字获取设置
function getDisbution($name){
	if (cache('setting')&&isset(cache('setting')[$name])) {
		$site_config = cache('setting')[$name];
	} else {
		$site_config = db("mall_setting")->where("inc_type",$name)->find();
		$setting[$name]=$site_config;
		cache("setting",$setting);
	}
	return iunserializer($site_config['value']);
}

/**验证码*/
 function check_sendcode($mobile, $code, $message){
		$where['mobile'] = $mobile;
		$where['code'] = $code;
		$where['message'] = '发送成功';
		$result =db('sms_code')->where($where)->find();
		// 10分钟有效期
		if(time() - strtotime($result['add_time']) > 600){
			return 2;
		}
		if($code == $result['code']){
			return 1;
		}else{
			return -1;
		}
	}
	
	/**
	 * 发送短信验证
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	function get_code($mobile, $template_no){
		// 获取短信模板
		$tem_w['title']='用户注册';
		
		$template = $tem=db("sms_template")->where($tem_w)->find();
		// 如果是验证码类型，则生成6位验证码
		if($template['type'] == 1){
			$code = rand(100000, 999999);
			$template['params'] = str_replace('${code}', $code, $template['params']);
			$data['code'] = $code;
		}
		$msg=sendsms($template['sign_name'],$mobile,$template['tid'],'code',$code,1);
		if($msg){
			return json(["code"=>200,"msg"=>'发送成功!']); 
		}else{
			return json(["code"=>408,"msg"=>'发送失败']); 
		}
		/*$data['mobile'] = $mobile;
		$data['title'] = $template['title'];
		$data['add_time'] = now_time();
		if(isset($msg->result)) {
			$data['message'] = '发送成功';
			db('sms_code')->insert($data);
			return json(["code"=>200,"msg"=>'发送成功!']); 
			//return $this->toSuccess('发送成功');
		}else{
			$data['result'] = 0;
			$data['message'] = '发送失败:';
			//$data['message'] = '发送失败:'.$msg->sub_msg;
			db('sms_code')->insert($data);
			if($msg->sub_code == "isv.BUSINESS_LIMIT_CONTROL"){
				$err = "超过发送次数，请稍后再试";
			}else{
				$err = "发送失败";
			}
			return json(["code"=>408,"msg"=>$err]); 
			//return $this->toError(408, $err);
		}*/
	}
	
	
	/**
	 * 获取微信openid
	 * 微信请求秘钥$code
	 */
	function cut_user_openId($wx_code){
		$code = $wx_code;//获取code
		$appid =config('wxpay_appid');
		$appsecret =config('wxpay_appsercet');
		$token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
		//通过code换取网页授权access_token
		$weixin =  file_get_contents($token_url);
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$openid = $array['openid'];//输出openid
		
		return $openid;
	}
	//判断是微信还是支付波啊打开1支付宝2微信
	function get_brower_type(){
		if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
			return 2;
		}elseif(strpos($_SERVER['HTTP_USER_AGENT'], 'AlipayClient') !== false) {
			return 1;
		}
	}
	/**
	 * 获取支付宝key
	 * 支付宝请求秘钥$aliy_key
	 */
	function cut_user_alibyid($aliy_key){
		import("payment.dpay.aop.AopClient");
		import("payment.dpay.aop.request.AlipaySystemOauthTokenRequest");
		$code = $aliy_key;//获取code
		$aop = new \AopClient ();
		$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = '2016030801195057';
		$aop->rsaPrivateKey = "MIIEowIBAAKCAQEAlzBlevyzabYxwRnG7mTo+KH39kxDXSaxb+iyfRSH9nw0eg7+Ltsx4VyA967S1LktOAo6dp05ty2bk9D5CQrQYu4ci+AKYmdGQNuGteJXeXt8NqBMQ4OgOKz2/wERXk4TZ5DTC4vKTyhhIFt+gcEKcKvY+lXkssY4+4/d9UCDSqErK8uLIQYAgpWNdcZj97YpsxOBxrze/u7bP1Ct2F/z6B1HLWaHYZmz+0Xlo94xCV1SoBs8BVpbDx0B0HTcUWTeQF7z4+SHIySEKtVv2YrW+hc2mLAHziFwikIWF+iuK0j/HN5/gYaAGd5GD0RHtwwi/sFgRjZ9GSEcV5tWm7V/DQIDAQABAoIBAHbedzs+SbV4qR/Aq5atwjoR5opApcosbN+m3gbXyJp0RzIcbZ7behlNCJ00V9EmkrX33MV7knBCLIsIh3SjivntaoZTLPb3adX+g6inf80k2KF+YNfIOoW1ADG4XjZ+PmV0CWqPiw23mr29EfbkltfFVUBlnf0tOooXMBTulwtp/MT0vhAYkNGtDnS8cfRnOekb0CKxTq3m/C+bNJKAUgOGMvxCORTHs1r8v5VJSzn/FwFcbiq6TExpy9D7ImQpbfw2KvXFc+9YJM9xbcMMFlP2sWOToHcC/JcskVJqJbnsxneW2OAsrl9uUkmJ8P5VOXbe+Bi5FF9OiP6pK3rwVGUCgYEAyFgF7O88g/JBv5egIjKNdT52h+oxPiaWNec2A+lymRVNXqmsvDcqI1LCz0mFqHJZOzl96aLbKTl+pbj8VvVSLCYnE/N7WZvGlHr8C3IIbXEUHKJQvn+qn8PJZLXxiT0GvJPSp8mPNlX2swnWn3AbL1Rkozg0m/P+TK8eaAs2jnsCgYEAwTCZ/Iw02KjNOl7utAk/jCVzPckAxfT//J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TpTLvQIDAQAB";
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		
		$request = new \AlipaySystemOauthTokenRequest ();
		$request->setGrantType("authorization_code");
		$request->setCode($code);
		$result = $aop->execute ( $request); 
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->user_id;
		
		return  $resultCode;
	}
	/**
	 * 获取支付宝key
	 * 支付宝请求秘钥$aliy_key
	 */
	function user_ali_id($aliy_key){
		import("payment.dpay.aop.AopClient");
		import("payment.dpay.aop.request.AlipaySystemOauthTokenRequest");
		$code = $aliy_key;//获取code
		$aop = new \AopClient ();
		$aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
		$aop->appId = '2017092808972929';
		$aop->rsaPrivateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCCICVD9KshbDmry/eW0Ut+0m+MIU2c7whGcWR1pszi34Fe3gURl6f4vYQrQKImzDuBOeWPfKIO7ccTnPl8vv9WJzv6AkxTfbadW2GYFqf5mZSIr2S/+wL/HAGaJeFtl2nT0DNLVwCZw1z8L9W3hQmWU+VRDhRvKdjVooh3gMfLjXyQGL5HmI+2YMIehEr4Av3MU6GhyTfHgE8PyP3DS3X8Doo+ZJEu2IHg9eT8BkLMFG60u+igA58PUI7fxbvdKoU6OGZwbLhCouIDbOncU+RAaBzyDeOfVjBuZY4LFhGNluP7TOuPo45IvDXXEltL1PsSz5ZAOlgJiN7fiLe5aqULAgMBAAECggEAR+NWcxqCSG6v1bdTSyDJYoEDWxky9ZYgrjoK0+yYmGX95NknV7a+925LzFFiw6hk31mK9yBVr4WxS6aXNlGWYpQ+UDpgzGdRMdHAMvOhTQWJx5GOSXl1CFcCk5SF27OgpYIKNH8WN9x0TGZo3YBD8abbs1Hh/B/USQIH/m1I86ycrkVprQIYP6z//RwNRw+BkMze06nx4rlleS9/ral1F4y33Ej2P2xGsbkEKcJs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Owvduz1CVKgxlwfPGbzzBVsmXzEjdnIjHpF6KjGo8MwaGd9wRmsVM3kqMvuHDbBfk4egoKClgzXLYPuUrNK6h5bsz6WY1/8tBlg2xMVg2AabNdHSEwI8z6PDELcfVmkkcOfS+fGzuCnvSYeEIpGzz1uQQPSbHfxNxCcCdkJ0SZfjduX2augFZ+1L/sorJgLxfNxWBcNCyJST1M3Eix5NHOA6iR3iSvkV4z0Yes1uMyv4Rp3nHFs8KMOZOsTmrqvpLWrhEkz7EH5j+v7fjRVmgb42Whz3HxP9tuhDgFC7YpbCfKURZZFqWYUTpTLvQIDAQAB";
		$aop->apiVersion = '1.0';
		$aop->signType = 'RSA2';
		$aop->postCharset='UTF-8';
		$aop->format='json';
		
		$request = new \AlipaySystemOauthTokenRequest ();
		$request->setGrantType("authorization_code");
		$request->setCode($code);
		$result = $aop->execute ( $request); 
		$responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
		$resultCode = $result->$responseNode->user_id;
		
		return  $resultCode;
	}
	//获取openid
	function user_wx_id($aliy_key){
		$code = input("code");//获取code
		$curl="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".config('wxpay_appid')."&secret=".config('wxpay_appsercet')."&code=$code&grant_type=authorization_code";
		$weixin =  file_get_contents($curl);//通过code换取网页授权access_token
		$jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
		$array = get_object_vars($jsondecode);//转换成数组
		$openid = $array['openid'];//输出openid
		return $openid;
	}

//oem资金变化日志
    function balance_change($o_id,$order_sn,$order_type,$balance,$operator,$message,$pay_type,$oem_id,$agency_id,$city_id){
    	$data['o_id'] 		= $o_id;
    	$data['order_sn'] 	= $order_sn;
    	$data['order_type'] = $order_type;
    	$data['balance'] 	= $balance;
    	$data['operator'] 	= $operator;
    	$data['message'] 	= $message;
    	$data['pay_type'] 	= $pay_type;
    	$data['oem_id'] 	= $oem_id;
    	$data['agency_id'] 	= $agency_id;
    	$data['city_id'] 	= $city_id;
    	$data['add_time'] 	= now_time();
    	
    	db('log_oem_charge')->insert($data);
    }
    
  	//oem佣金变化日志
    function commission_change($o_id,$order_sn,$order_type,$balance,$operator,$message,$pay_type,$oem_id,$agency_id,$city_id){
    	$data['o_id'] 		= $o_id;
    	$data['order_sn'] 	= $order_sn;
    	$data['order_type'] = $order_type;
    	$data['balance'] 	= $balance;
    	$data['operator'] 	= $operator;
    	$data['message'] 	= $message;
    	$data['pay_type'] 	= $pay_type;
    	$data['oem_id'] 	= $oem_id;
    	$data['agency_id'] 	= $agency_id;
    	$data['city_id'] 	= $city_id;
    	$data['add_time'] 	= now_time();
    	
    	db('log_oem_commission')->insert($data);
    }
    
    //提现日志
    function withdrawals_log($uid,$user_type,$balance,$actual_balance,$counter_fee,$cash_state,
    $remark,$thumb,$username,$deal_time,$fee,$bank_account,$bank_no,$bank_username,$bank_mobile,$oem_id){
    	$data['uid'] 			= $uid;
    	$data['user_type'] 		= $user_type;
    	$data['balance'] 		= $balance;
    	$data['actual_balance'] = $actual_balance;
    	$data['counter_fee'] 	= $counter_fee;
    	$data['cash_state'] 	= $cash_state;
    	$data['create_time'] 	= now_time();
    	$data['remark'] 		= $remark;
    	$data['thumb'] 			= $thumb;
    	$data['username'] 		= $username;
    	$data['deal_time'] 		= $deal_time;
    	$data['fee'] 			= $fee;
    	$data['bank_account'] 	= $bank_account;
    	$data['bank_no'] 		= $bank_no;
    	$data['bank_username'] 	= $bank_username;
    	$data['bank_mobile'] 	= $bank_mobile;
    	$data['oem_id'] 		= $oem_id;
    	
    	db('sys_withdrawals')->insert($data);
    }
    
    //用户佣金变化日志
	function user_commission_change($u_id,$order_sn,$order_type,$balance,$operator,
	$message,$pay_type,$oem_id,$agency_id,$city_id){
		$data['u_id'] 			= $u_id;
		$data['order_sn'] 		= $order_sn;
		$data['order_type'] 	= $order_type;
		$data['balance'] 		= $balance;
		$data['operator'] 		= $operator;
		$data['message'] 		= $message;
		$data['pay_type'] 		= $pay_type;
		$data['oem_id'] 		= $oem_id;
		$data['agency_id'] 		= $agency_id;
		$data['city_id'] 		= $city_id;
		$data['add_time'] 		= now_time();
    	
    	db('log_user_commission')->insert($data);
	}
	
	
	
	//用户余额变化日志
	function user_money_change($u_id,$order_sn,$order_type,$balance,$operator,
	$message,$pay_type,$oem_id,$agency_id,$city_id){
		$data['u_id'] 			= $u_id;
		$data['order_sn'] 		= $order_sn;
		$data['order_type'] 	= $order_type;
		$data['balance'] 		= $balance;
		$data['operator'] 		= $operator;
		$data['message'] 		= $message;
		$data['pay_type'] 		= $pay_type;
		$data['oem_id'] 		= $oem_id;
		$data['agency_id'] 		= $agency_id;
		$data['city_id'] 		= $city_id;
		$data['add_time'] 		= now_time();
    	
    	db('log_user_charge')->insert($data);
	}
	
	//商户资金变化日志
    function agent_money_change($agent_id,$chain_id,$clerk_id,$order_sn,$order_type,
    $store_balance,$operator,$message,$pay_type,$status_tinyint,$oem_id,$agency_id,$city_id,$salesman_id){
    	$data['agent_id'] 	= $o_id;
		$data['chain_id'] 	= $chain_id;
		$data['clerk_id'] 	= $clerk_id;
    	$data['order_sn'] 	= $order_sn;
    	$data['order_type'] = $order_type;
    	$data['store_balance'] 	= $store_balance;
    	$data['operator'] 	= $operator;
    	$data['message'] 	= $message;
    	$data['pay_type'] 	= $pay_type;
		$data['status_tinyint'] = $status_tinyint;
    	$data['oem_id'] 	= $oem_id;
    	$data['agency_id'] 	= $agency_id;
    	$data['city_id'] 	= $city_id;
		$data['salesman_id'] = $salesman_id;
    	$data['add_time'] 	= now_time();
    	
    	db('log_agent_charge')->insert($data);
    }
	